package com.hhkj.study.admin.teacher.service.biz.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hhkj.study.admin.resource.common.CommonValidateHandler;
import com.hhkj.study.admin.teacher.entity.Teacher;
import com.hhkj.study.admin.teacher.entity.TeacherScope;
import com.hhkj.study.admin.teacher.excel.TeacherExcelRes;
import com.hhkj.study.admin.teacher.model.podo.TeacherDo;
import com.hhkj.study.admin.teacher.model.podo.TeacherPo;
import com.hhkj.study.admin.teacher.model.req.TeacherReq;
import com.hhkj.study.admin.teacher.model.res.TeacherRes;
import com.hhkj.study.admin.teacher.service.base.TeacherScopeService;
import com.hhkj.study.admin.teacher.service.base.TeacherService;
import com.hhkj.study.admin.teacher.service.biz.TeacherBizService;
import com.hhkj.study.admin.teacher.service.extend.TeacherExtendService;
import com.hhkj.study.common.cache.GlobalCache;
import com.hhkj.study.common.handler.CommonHandler;
import com.hhkj.study.common.model.res.ExcelImportResultRes;
import com.ruoyi.common.base.biz.service.biz.BaseBizServiceImpl;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.enums.DictCodeEnum;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.excl.utils.ExcelUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* TeacherBizServiceImpl
*
* @author SERVER
* @since 2024-09-06
*/
@Service
public class TeacherBizServiceImpl extends BaseBizServiceImpl<Teacher, TeacherReq, TeacherRes, TeacherDo, TeacherPo, TeacherService, TeacherExtendService> implements TeacherBizService {

    @Resource
    private TeacherScopeService teacherScopeService;

    @Resource
    private GlobalCache globalCache;

    @Resource
    private CommonValidateHandler commonValidateHandler;


    @Override
    protected void afterPage(List<TeacherRes> teacherResList) {
        supplyTeacherInfo(teacherResList);
    }

    @Override
    protected void afterList(List<TeacherRes> teacherResList) {
        supplyTeacherInfo(teacherResList);
    }

    @Override
    protected void afterGetById(TeacherRes teacherRes) {
        if (ObjectUtil.isNull(teacherRes)) {
            return;
        }
        supplyTeacherInfo(Lists.newArrayList(teacherRes));
    }


    @Override
    protected void afterSave(TeacherReq teacherReq) {
        batchSave(teacherReq.getTeacherScopeIdList(), teacherReq.getId());
    }

    @Override
    protected void afterUpdate(TeacherReq teacherReq) {
        if (CollectionUtil.isEmpty(teacherReq.getTeacherScopeIdList())) {
            return;
        }
        LambdaQueryWrapper<TeacherScope> teacherScopeQuery = new LambdaQueryWrapper<>();
        teacherScopeQuery.eq(TeacherScope::getTeacherId, teacherReq.getId());
        List<TeacherScope> teacherScopeList = teacherScopeService.list(teacherScopeQuery);
        if (CollectionUtil.isEmpty(teacherScopeList)) {
            batchSave(teacherReq.getTeacherScopeIdList(), teacherReq.getId());
            return;
        }
        boolean isSuccess = teacherScopeService.remove(teacherScopeQuery);
        if (isSuccess) {
            batchSave(teacherReq.getTeacherScopeIdList(), teacherReq.getId());
        }
    }

    @Override
    protected void afterRemove(List<Long> idList) {
        LambdaQueryWrapper<TeacherScope> teacherScopeQuery = new LambdaQueryWrapper<>();
        teacherScopeQuery.in(TeacherScope::getTeacherId, idList);
        teacherScopeService.remove(teacherScopeQuery);
    }

    @Override
    public void export(TeacherReq req, HttpServletResponse response) {
        List<TeacherRes> list = list(req);
        if (CollectionUtil.isEmpty(list)) {
            throw new GlobalException("没有数据");
        }
        List<TeacherExcelRes> teacherExcelResList = BeanUtil.copyToList(list, TeacherExcelRes.class);
        ExcelUtils.exportExcelRuoYi(response, teacherExcelResList, TeacherExcelRes.class, "老师信息", "老师信息");
    }

    @Override
    public ExcelImportResultRes importTeacher(MultipartFile file, HttpServletRequest request) {
        List<TeacherExcelRes> teacherExcelResList = ExcelUtils.importExcelRuoYi(file, TeacherExcelRes.class, 1);
        if (CollectionUtil.isEmpty(teacherExcelResList)) {
            throw new GlobalException("没有数据");
        }
        ExcelImportResultRes excelImportResultRes = commonValidateHandler.commonValidate(teacherExcelResList, (res) -> checkUniqueTeacher((TeacherExcelRes) res));
        if (CollectionUtil.isEmpty(excelImportResultRes.getErrorList())) {
            List<Teacher> teacherList = BeanUtil.copyToList(teacherExcelResList, Teacher.class);
            this.getService().saveBatch(teacherList);
        }
        return excelImportResultRes;
    }

    /**
     * 校验教师对象中的唯一参数
     * @param res
     */
    private void checkUniqueTeacher(TeacherExcelRes res){

    }

    /**
     * 补充老师其他数据
     * @param teacherResList
     */
    private void supplyTeacherInfo(List<TeacherRes> teacherResList) {
        if (CollectionUtil.isEmpty(teacherResList)) {
            return;
        }

        List<Long> teacherIdList = teacherResList.stream().map(TeacherRes::getId).collect(Collectors.toList());
        LambdaQueryWrapper<TeacherScope> teacherScopeQuery = new LambdaQueryWrapper<>();
        teacherScopeQuery.in(TeacherScope::getTeacherId, teacherIdList);
        List<TeacherScope> teacherScopeList = teacherScopeService.list(teacherScopeQuery);
        Map<Long, List<Long>> teachScopeMap = Maps.newHashMap();
        if (CollectionUtil.isNotEmpty(teacherScopeList)) {
            // 获取老师对应的scopeIdList授课范围
            teachScopeMap = teacherScopeList.stream().collect(Collectors.groupingBy(TeacherScope::getTeacherId, Collectors.mapping(TeacherScope::getScopeType, Collectors.toList())));
        }
        Map<Long, String> dictMap = globalCache.cacheDictMap(Lists.newArrayList(DictCodeEnum.TEACHER_TAG.getCode(), DictCodeEnum.COURSE_TYPE.getCode()));
        Map<Long, List<Long>> finalTeachScopeMap = teachScopeMap;
        teacherResList.forEach(teacherRes -> {
            List<Long> teachScopIdList = finalTeachScopeMap.get(teacherRes.getId());
            if (CollectionUtil.isNotEmpty(teachScopIdList)) {
                teacherRes.setTeachScopeContent(CommonHandler.joinStr(dictMap, teachScopIdList, Constants.VERTICAL_LINE));
                teacherRes.setTeacherScopeMap(CommonHandler.getMapByDict(dictMap, teachScopIdList));
            }
            teacherRes.setTagContent(CommonHandler.joinStr(dictMap, teacherRes.getTagList(), Constants.VERTICAL_LINE));
            teacherRes.setTagMap(CommonHandler.getMapByDict(dictMap, teacherRes.getTagList()));
        });
    }

    /**
     * 批量保存老师授课范围
     * @param teachScopeIdList
     * @param teacherId
     */
    private void batchSave(List<Long> teachScopeIdList, Long teacherId){
        List<TeacherScope> teacherScopeList = teachScopeIdList.stream().map(scopeId -> {
            TeacherScope teacherScope = new TeacherScope();
            teacherScope.setTeacherId(teacherId);
            teacherScope.setScopeType(scopeId);
            return teacherScope;
        }).collect(Collectors.toList());
        teacherScopeService.saveBatch(teacherScopeList);
    }
}